package com.hrm.common.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.Getter;
import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;

import java.util.Date;
import java.util.Map;

@Getter
@Setter
@EnableConfigurationProperties(JwtUtils.class)
@ConfigurationProperties("jwt.config")
public class JwtUtils {
    //私钥名称
    private String key;
    //失效时间
    private long ttl;

    //获取token
    public String createJwt(String id, String name, Map<String, Object> map) {
        //获得失效时间
        long cur = System.currentTimeMillis();
        long exp = cur + ttl;
        JwtBuilder jwtBuilder = Jwts.builder()
                .signWith(SignatureAlgorithm.HS256, key)
                .setId(id)
                .setSubject(name)
                .setIssuedAt(new Date());
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            jwtBuilder.claim(entry.getKey(),entry.getValue());
        }
        if (ttl > 0) {
            jwtBuilder.setExpiration(new Date(exp));
        }
        return jwtBuilder.compact();
    }

    //解析token
    public Claims parseJwt(String token) {
        Claims claims = null;
        try {
            claims = Jwts.parser().setSigningKey(key).parseClaimsJws(token).getBody();
        }catch (Exception ignored){

        }
        return claims;
    }
}
